<template>
  <div><!--  <el-table :data="tableData" border stripe :header-cell-class-name="headerBg"-->
    <!--            @selection-change="handleSelectionChange"></el-table>-->
    <el-row>
      <el-col style="padding: 7px"
              :span="8" v-for="(merchandiseData,index) in tableData" :key="index"
              :offset="index > 0 ? tableData.total:0">
        <el-card :body-style="{ padding: '15px' }"  style="width: 95%;background: snow;box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)" shadow="hover">
          <el-image :src="merchandiseData.imgSrc" class="image">
            <div slot="error" class="image-slot" style="font-size:200px;height: 200px">
              <i class="el-icon-picture-outline"></i>
              <!--              <el-image :src="merchandiseData.imgSrc"></el-image>-->
            </div>
          </el-image>
          <div style="padding: 14px 0;font-size: xx-large">
            <el-row style="float: left; width: 100%">
              <el-col :span="12">商品名称：</el-col>
              <el-col :span="12"><span v-text="merchandiseData.names"></span></el-col>
            </el-row>
            <el-row style="float: left; width: 100%">
              <el-col :span="12">商品价格：</el-col>
              <el-col :span="12"><span v-text="merchandiseData.price"></span></el-col>
            </el-row>
            <el-row style="float: left; width: 100% ">
              <el-col :span="12">商品规格：</el-col>
              <el-col :span="12"><span v-text="merchandiseData.specification"></span></el-col>
            </el-row>
            <el-row style="float: left; width: 100%">
              <el-col :span="12">库存余量：</el-col>
              <el-col :span="12" v-text="merchandiseData.stock"></el-col>
            </el-row>
            <el-row style="float: left; width: 100%">
              <el-col :span="12">
                <el-button style="padding: 3px 0;font-size: xx-large" type="primary"
                           @click="handleEdit(merchandiseData.id)">商品详情
                </el-button>
              </el-col>
              <el-col :span="12">
                <el-button style="padding: 3px 0;font-size: xx-large" type="warning"
                           @click="handleAddMerchandise(merchandiseData.id)">快速加入订单
                </el-button>
              </el-col>
            </el-row>
          </div>
          <el-dialog title="商品详情" :visible.sync="dialogFormVisible" width="80%">
            <el-descriptions title="">
              <el-descriptions-item label="商品名称">{{ merchandise.names }}</el-descriptions-item>
              <el-descriptions-item label="价格">{{ merchandise.price }}</el-descriptions-item>
              <el-descriptions-item label="商品规格">{{ merchandise.specification }}</el-descriptions-item>
              <el-descriptions-item label="库存量">{{ merchandise.stock }}</el-descriptions-item>
              <el-descriptions-item label="订购数量">
                <el-input-number v-model="quantities" @change="handleChange" :min="0"
                                 :max="merchandise.stock"></el-input-number>
              </el-descriptions-item>
            </el-descriptions>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="handleAddMerchandiseDetail(merchandise.id)">加入订单</el-button>
            </div>
          </el-dialog>
          <div class="bottom clearfix">
            <!--            <time class="time">{{ currentDate }}</time>-->
          </div>
          <!--          <img :src="require(('../img'+merchandiseData.records).replace('../img',''))" alt="a">-->

          <!--          <img src="require(merchandiseData.imgSrc)" alt="">-->
        </el-card>
      </el-col>
    </el-row>
    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[5, 15, 45, 60]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
  </div>


</template>

<script>
export default {
  name: "Merchandises",
  data() {
    return {
      tableData: [],
      total: 0,
      names: "",
      price: 0,
      specification: "",
      merchandise: {},
      dialogFormVisible: false,
      quantities: 0,
      multipleSelection: [],
      pageNum: 1,
      pageSize: 5,
      headerBg: 'headerBg',
      currentDate: new Date(),
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {}
    }
  },
  created() {
    this.load()
  },
  methods: {
    load() {
      // 请求分页查询数据
      this.request.get(
          "/merchandise/page",
          {
            params: {
              pageNum: this.pageNum,
              pageSize: this.pageSize,
              names: this.names,
              specification: this.specification,
              // price: this.price
            }
          }
      ).then(res => {
        console.log(res)
        this.tableData = res.records
        this.total = res.total
      })
    },
    handleChange(value) {
      this.quantities = value;
      console.log(value);
    },
    handleAddMerchandise(merchandiseId) {
      const indexes = this.tableData.findIndex((role) => role.id === merchandiseId)
      const merchandiseDataForAdd = this.tableData[indexes]
      const userData = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {}
      this.request.post(
          "/shopping-cart",
          {
            // params:{
            userName: userData.username,
            userId: userData.id,
            merchandiseName: merchandiseDataForAdd.names,
            specification: merchandiseDataForAdd.specification,
            quantity: 1,
            price: merchandiseDataForAdd.price
            // }
          }
      ).then(res => {
        if (res.code === '200') {
          this.$message.success("成功加入 1件 <" + merchandiseDataForAdd.names + "> 到订单")
          this.dialogFormVisible = false
          this.load()
        } else {
          this.$message.error("加入失败，请联系管理员")
        }
      })
    },
    handleAddMerchandiseDetail(merchandiseId) {
      const indexes = this.tableData.findIndex((role) => role.id === merchandiseId)
      const merchandiseDataForAdd = this.tableData[indexes]
      const userData = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {}
      if (this.quantities === 0) {
        this.$message.error("订购数量为0，无法加入预定");
      } else {
        this.request.post(
            "/shopping-cart",
            {
              // params:{
              userName: userData.username,
              userId: userData.id,
              merchandiseName: merchandiseDataForAdd.names,
              specification: merchandiseDataForAdd.specification,
              quantity: this.quantities,
              price: merchandiseDataForAdd.price
              // }
            }
        ).then(res => {
          if (res.code === '200') {
            this.$message.success("成功加入" + this.quantities + "件 <" + merchandiseDataForAdd.names + "> 到订单")
            this.dialogFormVisible = false
            this.load()
          } else {
            this.$message.error("加入失败，请联系管理员")
          }
        })
      }
    },
    open() {
      this.$alert('这是一段内容', '标题名称', {
        confirmButtonText: '确定',
        callback: action => {
          this.$message({
            type: 'info',
            message: `action: ${action}`
          });
        }
      });
    },
    handleAdd() {
      this.dialogFormVisible = true
      this.merchandise = {}
    },
    handleEdit(merchandiseId) {
      const indexes = this.tableData.findIndex((role) => role.id === merchandiseId)
      this.merchandise = this.tableData[indexes]
      this.dialogFormVisible = true
    },
    handlerDel(id) {
      this.request.delete("/merchandise/delete/" + id).then(res => {
        if (res) {
          this.$message.success("删除商品信息成功！")
          // 删除成功后刷新页面
          this.load()
        } else {
          this.$message.error("删除商品信息失败！")
        }
      })
    },
    handleDelBatch() {
      let ids = this.multipleSelection.map(v => v.id) // {[1,,,],[2,,,]} ==>[1,2]
      this.request.post("/merchandise/deleteBatch", ids).then(res => {
        if (res) {
          this.$message.success("批量删除商品信息成功！")
          // 批量删除成功后刷新页面
          this.load()
        } else {
          this.$message.error("批量删除商品信息失败！")
        }
      })
    },
    hadleExcelImportSuccess() {
      this.$message.success("Excel文件导入成功！")
      this.load()
    },
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val
    },
    exp() {
      window.alert("即将跳转到下载页面")
      window.open("http://127.0.0.1:9090/merchandise/export")
    },
    reset() {
      this.names = ""
      this.specification = ""
      // this.price = ""
      //  清空表单后  刷新一下页面
      this.load()

    },
    save() {
      // 提交表单验证
      this.request.post(
          "/merchandise", this.merchandise).then(res => {
        if (res) {
          this.$message.success("提交商品信息成功！")
          // 成功后关闭弹窗，并且刷新页面
          this.dialogFormVisible = false
          this.load()
        } else {
          this.$message.error("提交商品信息失败！")
        }
      })
    },
    handleSizeChange(pageSize) {
      console.log(`每页 ${pageSize} 条`);
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      console.log(`当前页: ${pageNum}`);
      this.pageNum = pageNum
      this.load()
    }
  }
}
</script>

<style>
.time {
  font-size: 13px;
  color: #999;
}

.bottom {
  margin-top: 18px;
  line-height: 10px;
}

.button {
  padding: 0;
  float: right;
}

.image {
  width: 100%;
  height: 100%;
  display: block;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}
</style>